$(function(){
	var curPage = 1;
    var pageSize = 100;

	var changeTime = function(time) {
		var date = new Date(time);
		var year = date.getFullYear();
		var month = date.getMonth()+1;
		var day = date.getDate();
		var hour = date.getHours();
		var min = date.getMinutes();

		return year+'-'+month+'-'+day+' '+hour+':'+min;
	}

	var mes = {
		getList: function() {
			$.ajax({
			    url: wsCommon.host + '/api/memberComments/listMsg/receive',
			    dataType: wsCommon.jsonType,
			    success: function(res) {
					if(res.code == 1) {
						if(res.result) {
							var data = res.data;
							$('[data-role="total"] i').html(data.pager.total);
							$('[data-role="unread"]').html(data.unreadCount);
							$('[data-role="caogao"]').html(data.pager.total);

							var pager = res.data.pager;

							mes.initPaging(pager.pages, pager.total, res);
						} else {
							wsCommon.setCookie('go_back_link', window.location.href);
							window.location.href = './passport-login.html';
						}
					}
			    },
			    error: function() {
			        // console.log('接口返回失败');
			    }
			})
		},
		randerList: function(pageData) {
			var tpl = '';
			$.each(pageData, function(index, item) {
				tpl += '<tr class="handle action-view-detail" data-memReadStatus="'+item.memReadStatus+'" data-commentId="'+item.commentId+'">\
						  <td class="check"><input type="checkbox"  class="x-check op-check-all" data-id="'+item.commentId+'" data-role="delinput"></td>\
						  <td class="adressee">'+item.author+'</td>\
						  <td class="title">'+item.title+'</td>\
						  <td class="time">'+changeTime(item.time)+'</td>\
						  <td class="time"><a href="javascript:;" >回复</a></td>\
						</tr>\
						<tr class="detail active-bottom" style="display:none;">\
						  <td colspan="5">\
							<p class="detail-title">'+item.title+'</p>\
							<p class="detail-content">'+item.commentContent+' </p>\
							<div class="detail-reply">\
							  <div  class="action-reply-form">\
								<ul>\
								  <li class="form-item"><label for="" class="form-label">收件人：</label><span class="form-act">管理员</span></li>\
								  <li class="form-item"><label for="for_msg_title" class="form-label">标题：</label><span class="form-act"><input type="text" name="subject"  class="x-input" value="Re:'+item.title+'" data-role="title"></span></li>\
								  <li class="form-item"><label for="for_msg_content" class="form-label">内容：</label><span class="form-act"><textarea name="comment" class="x-input" cols="50" rows="5" data-role="value"></textarea></span></li>\
								  <li class="form-item">\
									<span class="form-act">\
									  <button class="btn btn-caution action-sendmsg" data-forCommentId="'+item.commentId+'" data-role="send"><span><span>发送</span></span></button>\
									  <button class="btn btn-simple action-savetodrafts" name="has_sent" data-role="sendsave" data-forCommentId="'+item.commentId+'"><span><span>保存到草稿箱</span></span></button>\
									</span>\
								  </li>\
								</ul>\
							  </div>\
							</div>\
						  </td>\
						</tr>';
			})
			$('[data-role="result"]').html(tpl);

			$(".action-view-detail").click(function(){
				$(this).next(".detail").toggle();
				console.log(!$(this).attr('data-memReadStatus'));
				if($(this).attr('data-memReadStatus') == 'false') {
					$(this).attr('data-memReadStatus', true)
					console.log(333);
					$.ajax({
		                url: wsCommon.host + '/api/memberComments/readMsg/'+$(this).attr('data-commentId'),
		                dataType: wsCommon.jsonType,
		                success: function(res) {
							if(res.code == 1) {
								if(res.result) {
									var value = Number($('[data-role="unread"]').html()) - 1;
									$('[data-role="unread"]').html(value)
								} else {
									wsCommon.setCookie('go_back_link', window.location.href);
									window.location.href = './passport-login.html';
								}
							}
		                },
		                error: function() {
		                    // console.log('分页接口失败');
		                }
		            });
				}
			})
		},
		getPageDates: function() {
            var self = this;

            $.ajax({
                url: wsCommon.host + '/api/memberComments/listMsg/receive',
                dataType: wsCommon.jsonType,
                data: {
					pageNum: curPage,
					pageSize: pageSize
				},
                success: function(res) {

                    // 同步页码
                    var totalPage = res.data.pager.pages;

                    var pageData = res.data.pager.list;
                    var pager = res.data.pager;
                    self.randerList(pageData);
                },
                error: function() {
                    // console.log('分页接口失败');
                }
            });
        },
		initPaging: function(totalPage, totalDataNum, res) {
            var self = this,
                ele = $('[data-role="dirPaging"]');
                if(totalDataNum > 0) {
                    ele.show();
                    var pagination = ele.pagination(totalDataNum, {
                        num_edge_entries: 1,
                        num_display_entries: 4,
                        callback: function(page_index) {
                            if(page_index == 0) {
                                var totalPage = res.data.pager.pages;

                                var pageData = res.data.pager.list;
                                var pager = res.data.pager;
                                mes.randerList(pageData);
                            } else {
                                curPage = page_index + 1;
                                mes.getPageDates();
                            }
                        },
                        items_per_page: pageSize,
                        prev_text: "&lt;&lt;上一页",
                        next_text: "下一页&gt;&gt;",
                        link_to: "javascript:;"
                    });

                }else {
                    ele.hide();
                    $('[data-role="result"]').html('<tr class="first"><td colspan="5" class="no-information">暂无消息</td></tr>')

                }
        },
		del: function(){
			$('[data-role="del"]').on('click', function() {
				var $input = $('[data-role="delinput"]:checked');
				var idList = '';
				var arr = [];
				$.each($input, function(index, item) {
					arr.push($(item).attr('data-id'));
				})
				idList = arr.join(',');
				if(idList != '' ) {
					$.ajax({
					    url: wsCommon.host + '/api/memberComments/deleteMsg/receive',
					    dataType: wsCommon.jsonType,
						data: {
							commentIds: idList,
						},
					    success: function(res) {
							if(res.code == 1) {
								if(res.result) {
									iosOverlay({
										text: "删除成功!",
										duration: 1500,
										onbeforehide: function() {
											window.location.reload();
										}
									});
								} else {
									wsCommon.setCookie('go_back_link', window.location.href);
									window.location.href = './passport-login.html';
								}
							} else {
								iosOverlay({
									text: res.reason,
									duration: 1500
								});
							}
					    },
					    error: function() {
					        // console.log('接口返回失败');
					    }
					})
				} else {
					iosOverlay({
						text: "请选择要删除的项目!",
						duration: 1500
					});
				}
			});

			$('.action-check-all').on('click', function() {
				if($(this).prop('checked')) {
					$('[data-role="delinput"]').prop('checked', true);
				} else {
					$('[data-role="delinput"]').prop('checked', false);
				}
				// $('[data-role="delinput"]').prop('checked', true);
			})
		},
		sunmit: function() {
			$(document).on('click', '[data-role="send"]', function() {
				var $this= $(this);
				var title = $this.closest('tr').find('[data-role="title"]').val();
				var value = $this.closest('tr').find('[data-role="value"]').val();
				if(title == '') {
					iosOverlay({
						text: "标题不能为空!",
						duration: 1500
					});
					return;
				}
				if(value == '') {
					iosOverlay({
						text: "内容不能为空!",
						duration: 1500
					});
					return;
				}

				$.ajax({
					url: wsCommon.host + '/api/memberComments/sendMsg',
					dataType: wsCommon.jsonType,
					data: {
						toId: 1,
						title: title,
						commentContent: value,
						hasSent: true,
						forCommentId: $this.attr('data-forCommentId')
					},
					success: function(res) {
						if(res.code == 1) {
							if(res.result) {
								iosOverlay({
									text: "发送成功!",
									duration: 1500,
									onbeforehide: function() {
										window.location.reload();
									}
								});
							} else {
								iosOverlay({
									text: res.reason,
									duration: 1500
								});
							}
						} else {
							iosOverlay({
								text: res.reason,
								duration: 1500
							});
						}
					},
					error: function() {
						// console.log('登录显示接口返回失败');
					}
				})
			})


			$(document).on('click', '[data-role="sendsave"]', function() {
				var $this= $(this);
				var title = $this.closest('tr').find('[data-role="title"]').val();
				var value = $this.closest('tr').find('[data-role="value"]').val();
				if(title == '') {
					iosOverlay({
						text: "标题不能为空!",
						duration: 1500
					});
					return;
				}
				if(value == '') {
					iosOverlay({
						text: "内容不能为空!",
						duration: 1500
					});
					return;
				}

				$.ajax({
					url: wsCommon.host + '/api/memberComments/sendMsg',
					dataType: wsCommon.jsonType,
					data: {
						toId: 1,
						title: title,
						commentContent: value,
						hasSent: false,
						forCommentId: $this.attr('data-forCommentId')
					},
					success: function(res) {
						if(res.code == 1) {
							if(res.result) {
								iosOverlay({
									text: "保存到草稿箱成功!",
									duration: 1500,
									onbeforehide: function() {
										window.location.reload();
									}
								});
							} else {
								iosOverlay({
									text: res.reason,
									duration: 1500
								});
							}
						} else {
							iosOverlay({
								text: res.reason,
								duration: 1500
							});
						}
					},
					error: function() {
						// console.log('登录显示接口返回失败');
					}
				})
			})
		},
		getShoujian: function() {
			$.ajax({
			    url: wsCommon.host + '/api/memberComments/listMsg/drafts',
			    dataType: wsCommon.jsonType,
			    success: function(res) {
					if(res.code == 1) {
						if(res.result) {
							var data = res.data;
							$('[data-role="shoujian"]').html(data.pager.total);
						} else {
							wsCommon.setCookie('go_back_link', window.location.href);
							window.location.href = './passport-login.html';
						}
					}
			    },
			    error: function() {
			        // console.log('接口返回失败');
			    }
			})
		},
		init: function() {
			this.getShoujian();
			this.getList();
			this.del();
			this.sunmit();
		}
	}

	mes.init();
})
